"ui";
import rhino from "rhino";
import ui from "ui";
import {
    Worker
} from "worker_threads";

rhino.install();

class MainActivity extends ui.Activity {

    onCreate(savedInstance) {
        super.onCreate(savedInstance);
    }
    
    onCreateOptionsMenu(menu) {
        super.onCreateOptionsMenu(menu);
        menu.add("关于");
        return true;
    }
    
    onOptionsItemSelected(item) {
        super.onOptionsItemSelected(item);
        if (item.getTitle() == "关于") {
            this.aboutAlertDialog();
        }
        return true;
    }
    
    aboutAlertDialog() {
        const MaterialAlertDialogBuilder = com.google.android.material.dialog.MaterialAlertDialogBuilder;
        new MaterialAlertDialogBuilder(this)
            .setTitle("关于")
            .setMessage(`这是一个 JS 语法分析工具，也可以压缩 JS 代码，其可通过 Transformer 进行深度优先遍历对 AST Tree 增删改查，然后进行 Code Generate 生成目标代码
            
            本语法分析规范是 acorn.js, AST Node dump 出来的属性和名称是一致的
            软件没必要加密, 所以我就直接没有加密了
            
            软件作者: SuMuCheng
            我的 QQ: 3578557729
            ParseJS Github: https://github.com/CaiMuCheng/ParseJS
            QQ 交流群: 1031450748
            `.split("\n").map((value) => value.trim()).join("\n"))
            .setPositiveButton("确定", null)
            .show();
    }

    onContentViewSet(view) {
        const binding = view.binding;
        const source = binding.source;
        const target = binding.target;
        const ast = binding.ast;
        const generateASTJson = binding.generateASTJson;
        const format = binding.format;
        const exprContainer = binding.exprContainer;
        const computedGroup = binding.computedGroup;
        const autoComputed = binding.autoComputed;
        const onComputed = binding.onComputed;
        const offComputed = binding.offComputed;
        const button = binding.button;
        
        this.setSupportActionBar(binding.toolbar);
        binding.description.setText(`The ECMAScript (aka JavaScript) lexical analysis and syntax analysis implemention that named NiceJS.
            Corresponds to ECMAScript 6
            The AST standard is acorn.js
            
            What's this?
            This is the lexical analysis and syntax analysis implemention for ECMAScript. <br/>
            You can modify the source after run code.
            
            Features
            - Variable declaration
            - Function declaration
            - Block statement & If statement & Loop statement & Empty statement
            - Unary expression & Binary expression & Conditional expression
            - Sequence expression
            - Array expression & Object expression
            - Function expression
            
            Get started - Linux
            -----------------------------
            git clone https://github.com/CaiMuCheng/ParseJS.git
            cd ParseJS
            npm run start
            -----------------------------`.split("\n").map((value) => value.trim()).join("\n"));
        const toast = message => android.widget.Toast.makeText(this, message, 0).show();
        let computedMode = "default";
        computedGroup.setOnCheckedChangeListener((group, checkedId) => {
            const radio = view.findViewById(checkedId);
            if (autoComputed.isChecked()) {
                computedMode = "default";
            }
            if (onComputed.isChecked()) {
                computedMode = "onComputed";
            }
            if (offComputed.isChecked()) {
                computedMode = "offComputed";
            }
        });

        button.on("click", () => {
            const sourcePath = source.getText().toString();
            const astPath = ast.getText().toString();
            const targetPath = target.getText().toString();
            const generateASTJsonChecked = generateASTJson.isChecked();
            const formatChecked = format.isChecked();
            const exprContainerChecked = exprContainer.isChecked();
            
            if (sourcePath == "") {
                toast("源文件路径不能为空");
                return;
            }
            if (astPath == "") {
                toast("AST JSON 生成路径不能为空");
                return;
            }
            if (targetPath == "") {
                toast("目标生成路径不能为空");
                return;
            }

            const dialog = new android.app.ProgressDialog(this);
            dialog.setMessage("正在读取源文件....");
            dialog.setCancelable(true);
            dialog.show();
            
            const worker = new Worker("./util.node.js", {
                workerData: {
                    sourcePath, astPath, targetPath,
                    computedMode, 
                    generateASTJsonChecked, formatChecked, exprContainerChecked
                }
            });
            worker.on("message", (result) => {
                if (result.text) {
                    dialog.setMessage(result.text);
                }
                if (result.error) {
                    toast(result.error);
                }
                if (result.dismiss) {
                    dialog.dismiss();
                }
                if (result.success) {
                    toast("代码生成成功");
                }
            });
        });
    }

    get layoutXml() {
        return `
            <column>
                <com.google.android.material.appbar.MaterialToolbar
                    w="*"
                    h="auto"
                    title="JS 语法分析"
                    id="toolbar"
                />
                <com.google.android.material.card.MaterialCardView
                    w="*"
                    h="200"
                    marginLeft="15"
                    marginRight="15"
                    radius="16"
                    clickable="true"
                    strokeWidth="0"
                    cardElevation="4"
                    cardBackgroundColor="#FFFFFFFF"
                    >
                    
                        <column w="*" h="*" margin="15">
                            <androidx.core.widget.NestedScrollView
                                scrollbars="none"
                                >
                                    <column id="descriptionScroll">
                                    <text text="ParseJS" textSize="16sp"/>
                                    <text id="description" textSize="12sp" marginTop="10" textIsSelectable="true"/>
                                    </column>
                            </androidx.core.widget.NestedScrollView>
                        </column>
                    
                </com.google.android.material.card.MaterialCardView>
                
                <com.google.android.material.card.MaterialCardView
                    w="*"
                    h="*"
                    margin="15"
                    radius="16"
                    clickable="true"
                    strokeWidth="0"
                    cardElevation="4"
                    cardBackgroundColor="#FFFFFFFF"
                    >
                    
                    <androidx.core.widget.NestedScrollView
                                scrollbars="none"
                                margin="15">
                        <column>
                            <text text="文件" textSize="16sp" />
                            <text text="源文件路径" marginTop="15" textSize="14sp" />
                            <input id="source" text="/storage/emulated/0/source.js" textSize="14sp" singleLine="true"/>
                            <text text="目标生成路径" textSize="14sp" marginTop="15"/>
                            <input id="target" text="/storage/emulated/0/generated.js" textSize="14sp" singleLine="true"/>
                            <text text="AST JSON 生成路径" textSize="14sp" marginTop="15"/>
                            <input id="ast" text="/storage/emulated/0/AST.json" textSize="14sp" singleLine="true"/>
                            <text text="代码生成器选项" textSize="16sp" marginTop="15" />
                            <checkbox id="generateASTJson" text="生成 AST JSON" textSize="12sp" />
                            <checkbox id="format" text="格式化代码" textSize="12sp" />
                            <checkbox id="exprContainer" text="对表达式语句嵌套括号" textSize="12sp" />
                            <radiogroup id="computedGroup">
                                <radio checked="true" id="autoComputed" text="自动 Computed" textSize="12sp" />
                                <radio id="onComputed" text="强制启用 Computed" textSize="12sp" />
                                <radio id="offComputed" text="强制禁用 Computed" textSize="12sp" />
                            </radiogroup>
                            <com.google.android.material.card.MaterialCardView
                                id="button"
                                width="*"
                                height="40"
                                strokeWidth="0"
                                radius="40"
                                focusable="true"
                                clickable="true"
                                cardBackgroundColor="#FF2881FF">
                                
                                <text
                                    w="*"
                                    h="*"
                                    gravity="center"
                                    textSize="13sp"
                                    textColor="#FFF5F5F7">分析并生成</text>
                                
                            </com.google.android.material.card.MaterialCardView>
                        </column>
                    </androidx.core.widget.NestedScrollView>
                    
                    </com.google.android.material.card.MaterialCardView>
            </column>
        `;
    }

}

ui.setMainActivity(MainActivity);
ui.activityLifecycle.on("all_activities_destroyed", () => {
    // exit process
    process.exit(0);
});